from flask import Blueprint, request, jsonify
from sqlalchemy import or_

from apps.libs.redprint import Redprint
from apps.validators.forms import BookSearchForm
from apps.models.book import Book

api = Redprint('book')

@api.route('/search', methods=['POST', 'GET'])
def get_book():
    form = BookSearchForm().validate_for_api()
    q = '%' + form.q.data + '%'
    # 书籍模糊查询多个字段
    books = Book.query.filter(or_(Book.title.like(q), Book.publisher.like(q))).all()
    return jsonify(books)

@api.route('/<isbn>/detail')
def detail(isbn):
    book = Book.query.filter_by(isbn=isbn).first_or_404()
    return jsonify(book)